#!/bin/sh

#
usage() {
cat << EOF
Usage: buildDockerImage.sh -v [version] [-c]
Builds a Docker Image for BES AppServer.
Parameters:
   -v: version to build. Required.
       Choose one of: $(for i in $(ls -d */); do echo -n "${i%%/}  "; done)
   -c: enables Docker image layer cache during build
EOF
exit 0
}

# Parameters
# 导出的镜像文件名称
VESION="10.0.0.2523"
IMAGE_NAME="bes10.0.0.2523-x86-jdk8"
NOCACHE=true
while getopts "hscn:v:j:" optname; do
  case "$optname" in
    "h")
      usage
      ;;
    "v")
      VERSION="$OPTARG"
      echo "Set BES Appserver's version: $VERSION"
      ;;
    "c")
      NOCACHE=false
      echo "Set NOCACHE to false"
      ;;
    *)
    # Should not occur
      echo "Unknown error while processing options inside buildDockerImage.sh"
      ;;
  esac
done

if [ "$VERSION" == "10.0.0.2523" ]; then
   DIST="BES-AppServer-Standard-${VERSION}.tar.gz"
   echo "Version= $VERSION Distribution= $DIST"
else
   echo "Unknown error while find BES Appserver distribution"
fi

BUILD_DIR=$VERSION

for i in $(ls -f $BUILD_DIR/); do 
  if echo "${i%%/}" | grep -iq "jdk"; then
    JDK_DIST=$i
    echo "JDK Distributin: $JDK_DIST"
    break;
  fi
done


# 需要变更变量 DOCKER_REPOSITORY DOCKER_TAG IMAGE_NAME JDK_TAR JDK_PACKAGE 以下值以 Kylin-V10-SP2-X86为例
# 镜像仓库
DOCKER_REPOSITORY="bessystem/appserver"
# 镜像标签
DOCKER_TAG=$VERSION
cd $BUILD_DIR

mkdir work && tar -zxf ${JDK_DIST} -C work && export JDK_DIR=$(ls -A work/) && rm -rf work
if ! [ -d patch ]; then mkdir patch; fi

# 删除原有镜像，并根据Dockerfile重新生成镜像
docker rmi -f ${DOCKER_REPOSITORY}:${DOCKER_TAG} 1>/dev/null 2>&1;

docker build --force-rm=$NOCACHE --no-cache=$NOCACHE  --progress=plain --build-arg JDK_DIR=$JDK_DIR  --build-arg JDK_DIST=$JDK_DIST --build-arg BES_DIST=$DIST -t ${DOCKER_REPOSITORY}:${DOCKER_TAG} -f Dockerfile ./ || {
  echo "There was an error building the image."
  exit 1
}
